<template>
	<div>
		<div class="container">
			<div class="box">
				<div class="text">书名:</div>
				<input type="text" class="bookname" v-model="bookname" />
			</div>
			<div class="box">
				<div class="text">作者:</div>
				<input type="text" class="author" v-model="author" />
			</div>
			<div class="box">
				<div class="text">出版社:</div>
				<input type="text" class="publisher" v-model="publisher" />
			</div>
			<button class="add" @click="onAdd">添加</button>
		</div>
		<table>
			<thead>
				<tr>
					<th v-for="(item, index) in tableList" :key="index">
						{{ item }}
					</th>
				</tr>
			</thead>
			<tbody>
				<tr v-for="item in data" :key="item.id">
					<td v-for="(value, key) in item" :key="key">
						{{ value }}
					</td>
					<button @click="onDelete(item.id)">删除</button>
				</tr>
			</tbody>
		</table>
	</div>
</template>

<script>
import request from "../utils/request";
// API
const baseURL = "http://www.liulongbin.top:3006";
const searchAPI = "/api/getbooks";
const addAPI = "/api/addbook";
const delAPI = "/api/delbook";
export default {
	data() {
		return {
			data: [],
			tableList: ["Id", "书名", "作者", "出版社", "操作"],
			bookname: "",
			author: "",
			publisher: "",
		};
	},
	created() {
		// 获取data
		this.onSearch();
	},
	methods: {
        // axios 引用到单独的util文件的写法
		async onSearch() {
			const res = await request({
				method: "get",
				url: searchAPI,
			});
			this.data = res.data.data;
		},
		async onAdd() {
            // axios 引用到main.js的写法
			const res = await this.http({
				method: "post",
				url: baseURL + addAPI,
				data: {
					bookname: this.bookname,
					author: this.author,
					publisher: this.publisher,
				},
			});
			alert(res.data.msg);
			this.onSearch();
		},
		async onDelete(id) {
			const res = await this.http({
				method: "get",
				url: baseURL + delAPI,
				params: {
					id,
				},
			});
			alert(res.data.msg);
			this.onSearch();
		},
	},
};
</script>

<style scoped>
.container {
	width: 1200px;
	height: 50px;
	display: flex;
	justify-content: space-between;
}
.box {
	display: flex;
	line-height: 50px;
	text-align: center;
}
.text {
	width: 80px;
}
table {
	width: 1200px;
	height: 200px;
	border: 1px solid pink;
	margin-top: 50px;
	border-spacing: 0;
}
td,
th {
	border-bottom: 1px solid pink;
	border-right: 1px solid pink;
}
</style>